package org.naxx.security.naxxlet.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.naxx.security.common.IndeterminateExpressionException;
import org.naxx.security.model.match.MatchParentType;
import org.naxx.security.model.result.TargetEvaluationResult;

// e.g. one subject with multiple matches
public abstract class XAbstractMatchContainer {
	
	private static final Logger logger = Logger.getLogger(XAbstractMatchContainer.class);
	
	private MatchParentType matchParentType;
	protected List<XAbstractMatch> matches;
	
	public XAbstractMatchContainer() {
		this.matches = new ArrayList<XAbstractMatch>();
	}
	
	public final TargetEvaluationResult evaluate() {
		return exec();
	}
	
	protected TargetEvaluationResult exec() {
		boolean atLeastOneIndeterminate = false;
		for(XAbstractMatch match : this.matches) {
			try {
				Boolean result = match.evaluate();
				if(Boolean.FALSE.equals(result)) {
					return TargetEvaluationResult.NO_MATCH;
				}
			} catch (IndeterminateExpressionException e) {
				atLeastOneIndeterminate = true;
				logger.warn("Exception while evaluating match container", e);
			}
		}
		if(atLeastOneIndeterminate) {
			return TargetEvaluationResult.INDETERMINATE;
		}
		return TargetEvaluationResult.MATCH;
	}
	
	public void addXMatch(XAbstractMatch xMatch) {
		this.matches.add(xMatch);
	}

	public MatchParentType getMatchParentType() {
		return matchParentType;
	}

	public abstract void setMatchParentType(MatchParentType matchParentType);
}
